﻿using MES.Desktop.Entities;
using MES.Desktop.IService;
using MES.Desktop.Service;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace MES.Desktop.ViewModels
{
    public class LoginViewModel : BindableBase, IDialogAware
    {
        public string Title { get; set; } = "MES系统登录";

        public event Action<IDialogResult> RequestClose;

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {

        }

        public void OnDialogOpened(IDialogParameters parameters)
        {

        }

        private bool _isShowCheck;

        public bool IsShowCheck
        {
            get { return _isShowCheck; }
            set
            {
                SetProperty<bool>(ref _isShowCheck, value);
                if (value) Blur = 12;
                else Blur = 0;
            }
        }
        private int _blur = 0;

        public int Blur
        {
            get { return _blur; }
            set { SetProperty<int>(ref _blur, value); }
        }

        public string UserName { get; set; } = "admin";
        public string Password { get; set; } = "123456";

        private string _errorInfo;

        public string ErrorInfo
        {
            get { return _errorInfo; }
            set { SetProperty<string>(ref _errorInfo, value); }
        }

        public DelegateCommand LoginCommand { get; set; }
        public DelegateCommand LoadedCommand { get; set; }
        public DelegateCommand CloseCommand { get; set; }

        IFileService _fileService;
        IUserService _userService;
        IAuthServer _authServer;
        GlobalValues _globalValues;
        public LoginViewModel(
            IFileService fileService,
            IUserService userService,
            IAuthServer authServer,
            GlobalValues globalValues)
        {
            _fileService = fileService;
            _userService = userService;
            _authServer=authServer;
            _globalValues = globalValues;
            LoginCommand = new DelegateCommand(DoLogin);
            LoadedCommand = new DelegateCommand(DoLoaded);
            CloseCommand = new DelegateCommand(DoClose);
        }

        private void DoClose()
        {
            RequestClose?.Invoke(new DialogResult(ButtonResult.Cancel) );
        }

        private void DoLoaded()
        {
            IsShowCheck = true;

            Task.Run(async () =>
            {
                try
                {
                    //await Task.Delay(4000);

                    //1、获取服务端最新文件列表            
                    var files_server = _fileService.GetServerUpgradeFiles().ToList();
                    // 2、获取本地记录最新文件列表
                    var files_local = _fileService.GetLocalUpgradeFiles().ToList();

                    // 以服务端文件列表为基础进行文件判断
                    List<string> update_file = new List<string>();
                    foreach (var sf in files_server)
                    {
                        if (files_local.Exists(f => f.fileName == sf.fileName &&
                                        f.fileMd5 != sf.fileMd5) ||
                            !files_local.Exists(f => f.fileName == sf.fileName))
                        {
                            // 这个文件是需要下载的(名称、路径、大小)
                            // Zhaoxi.PMS.Client.BLL.dll|UpgradeFiles|100
                            update_file.Add(sf.fileName + "|" + sf.filePath + "|" + sf.length + "|" + sf.fileMd5);
                        }
                    }

                    // 服务器拿到文件列表中的文件都得下载
                    if (update_file.Count > 0)
                    {
                        // 启动更新程序，并且将更新文件列表传给它
                        Process.Start("MES.Desktop.Upgrade.exe", update_file);
                        // 

                        Application.Current.Dispatcher.Invoke(new Action(() =>
                        {
                            System.Environment.Exit(0);// 结束进程
                        }));
                    }
                }
                catch (Exception ex)
                {
                    ErrorInfo = ex.Message;
                }
                finally
                {
                    IsShowCheck = false;
                }
            });
        }

        private void DoLogin()
        {
            // 将用户名和密码提交到WebApi，检查状态，将状态写入State属性
            // 需要返回用户相关信息  Token
            Task.Run(() =>
            {
                try
                {
                    var user = _userService.Login(UserName, Password);

                    if (user.status == 0)
                        throw new Exception("用户被锁定");
                    // 登录成功
                    string token = _authServer.AuthAccount(user);
                    _globalValues.Token = token;
                    _globalValues.UserId = user.userId;
                    _globalValues.UserName = user.userName;

                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        DialogParameters dps = new DialogParameters();
                        dps.Add("user", user);
                        RequestClose?.Invoke(new DialogResult(ButtonResult.OK, dps));
                    });
                }
                catch (Exception ex)
                {
                    this.ErrorInfo = ex.Message;
                }
            });
        }

    }
}
